package cn.rui.decoration.filter;

import cn.rui.decoration.pojo.vo.UserVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//urlPatterns里面的路径必须/开头, 如果书写错误 会导致工程无法启动
@WebFilter(filterName = "MyFilter",urlPatterns = {"/admin.html","/insertProduct.html","/detail.html","/orderdetail.html"})
public class MyFilter implements Filter {
//过滤器初始化方法
public void init(FilterConfig config) throws ServletException {
}
//过滤器销毁方法
public void destroy() {
}
@Override  //当请求经过过滤器时执行的方法
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest rt = (HttpServletRequest) request;
HttpServletResponse re = (HttpServletResponse) response;
//从请求对象中获取Session
HttpSession session = rt.getSession();
//获取Session中的用户对象
UserVO user = (UserVO) session.getAttribute("user");
if (user!=null){//登录了
chain.doFilter(request, response);//放行
}else{
re.sendRedirect("/login.html");//重定向到登录页面
}

}
}
